package com.cloudkinto.service.analysis.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloudkinto.common.common.DateUtils;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.*;
import com.cloudkinto.entity.CompanyDo;
import com.cloudkinto.entity.ProductInfoDo;
import com.cloudkinto.entity.StorageDo;
import com.cloudkinto.extentity.*;
import com.cloudkinto.service.analysis.AnalysisService;
import com.cloudkinto.service.analysis.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhujiale
 * @description
 * @date 2022/11/30
 */
@Service
public class AnalysisServiceImpl implements AnalysisService {
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private StorageDao storageDao;
    @Autowired
    private OrderOutputDao orderOutputDao;
    @Autowired
    private StockRecordDao stockRecordDao;
    @Autowired
    private ProductInfoDao productInfoDao;

    @Override
    public SingleResult init(Long companyId, String[] storageIdList) {
        List<StorageDo> storageList = storageDao.selectList(new QueryWrapper<StorageDo>());
        List<CompanyDo> companyList = companyDao.selectList(new QueryWrapper<CompanyDo>());
        List<InitRes> resList = new ArrayList<>();
        for (StorageDo st : storageList) {
            InitRes initRes = new InitRes();
            initRes.setId(st.getId());
            initRes.setName(st.getStorageName());
            resList.add(initRes);
        }
        List<InitRes> resList1 = new ArrayList<>();
        for (CompanyDo ct : companyList) {
            InitRes initRes = new InitRes();
            initRes.setId(ct.getId());
            initRes.setName(ct.getName());
            resList1.add(initRes);
        }


//        List<ProductInfoDo> productInfoDoList = productInfoDao.selectList(new LambdaQueryWrapper<ProductInfoDo>()
//                .eq(ProductInfoDo::getCompanyId, companyId).orderByAsc(ProductInfoDo::getCommoditySku));
//        List<Long> storageId = new ArrayList<>();
//        if (storageIdList != null && storageIdList.length > 0) {
//            for (String s : storageIdList) {
//                storageId.add(Long.parseLong(s));
//            }
//        }
//        List<StockAgeSkuDTO> skuList = stockRecordDao.getStockAgeSkuList(storageId, null, companyId);
//        List<Map<String, Object>> productResList = new ArrayList<>();
//        int index = 0;
//        for (StockAgeSkuDTO productInfoDo : skuList) {
//            if (index == 100 || index >= skuList.size()) {
//                break;
//            }
//            Map<String, Object> map = new HashMap<>();
//            map.put("id", productInfoDo.getId());
//            map.put("sku", productInfoDo.getCommoditySku());
//            productResList.add(map);
//            index ++;
//        }

        Map map = new HashMap();
        map.put("storageList", resList);
        map.put("companyList", resList1);
//        map.put("skuList", productResList);

        return SingleResult.success(map);
    }

    @Override
    public SingleResult customerAnalysis() {
        CustomerAnalysisRes res = companyDao.getCustomerAnalysisInfo();
        //获取当年会员趋势图即每个月的会员数量
        List<CustomerAnalysisDto> customerAnalysisDtoList = companyDao.getCustomerAnalysisList();
        List<CustomerAnalysisRes.ItemsDTO> itemList = new ArrayList<>();
        for (CustomerAnalysisDto dto : customerAnalysisDtoList) {
            CustomerAnalysisRes.ItemsDTO itemsDto = new CustomerAnalysisRes.ItemsDTO();
            itemsDto.setId(dto.getId());
            itemsDto.setDate(dto.getDate());
            itemsDto.setNum(dto.getNum());
            itemList.add(itemsDto);
        }
        res.setYearMonthList(itemList);
        return SingleResult.success(res);
    }

    @Override
    public Object storageSituation(AnalysisReq req, Long companyId) {
        Map map = new HashMap();
        map.put("startDate", req.getStartDate());
        map.put("endDate", req.getEndDate());
        map.put("storageId", req.getStorageId());
        map.put("companyId", companyId);
        int days = DateUtils.differentDaysByMillisecond(DateUtils.stringFormatToDate(req.getStartDate()), DateUtils.stringFormatToDate(req.getEndDate()));
        map.put("chainStartDate", DateUtils.dateFormatToString(DateUtils.passingDate(DateUtils.stringFormatToDate(req.getStartDate()), -days), null));
        map.put("chainEndDate", DateUtils.dateFormatToString(DateUtils.passingDate(DateUtils.stringFormatToDate(req.getEndDate()), -days), null));
        //获取入出库对比数据
        StorageSituationDto storageSituationDto = orderOutputDao.getStorageSituation(map);
        //一件代发出货对比
        List<OutputChannelDto> channelDto1 = orderOutputDao.getOutputDeliveryChannel(map);
        //FBA转运出货对比
        List<OutputChannelDto> channelDto2 = orderOutputDao.getOutputFBAChannel(map);

        Map resultMap = new HashMap();
        resultMap.put("storageSituationDto", storageSituationDto);
        resultMap.put("channelDto1", channelDto1);
        resultMap.put("channelDto2", channelDto2);
        return SingleResult.success(resultMap);
    }

    @Override
    public SingleResult stockAgeAnalysis(StockAgeReq req, Long companyId) {
        List<StockAgeDto> stockList = stockRecordDao.getStockAgeAnalysis(req.getStorageIdList(), companyId);
        StockAgeRes res = new StockAgeRes();
        List<StockAgeRes.CompanyInfo> companyInfoList = new ArrayList<>();
        for (StockAgeDto et : stockList) {
            StockAgeRes.CompanyInfo companyInfo = new StockAgeRes.CompanyInfo();
            BeanUtils.copyProperties(et, companyInfo);
            companyInfoList.add(companyInfo);
        }
        res.setCompanyInfoList(companyInfoList);
        res.setLess60NumAll(stockList.stream().mapToInt(StockAgeDto::getLess60Num).sum());
        res.setSixtyTo180NumAll(stockList.stream().mapToInt(StockAgeDto::getSixtyTo180Num).sum());
        res.setMore180NumAll(stockList.stream().mapToInt(StockAgeDto::getMore180Num).sum());
        res.setLess60VolumeAll(stockList.stream().mapToDouble(StockAgeDto::getLess60Volume).sum());
        res.setSixtyTo180VolumeAll(stockList.stream().mapToDouble(StockAgeDto::getSixtyTo180Volume).sum());
        res.setMore180VolumeAll(stockList.stream().mapToDouble(StockAgeDto::getMore180Volume).sum());

        List<StockAgeSkuDTO> skuList = stockRecordDao.getStockAgeSkuList(req.getStorageIdList(), req.getProductIdList(), companyId);
        List<StockAgeSkuDTO> skuNumList = skuList.stream()
                .filter(s -> s.getSkuNum() != 0)
                .sorted((s1, s2) -> s1.getSkuNum().compareTo(s2.getSkuNum()))
                .collect(Collectors.toList());
        List<StockAgeSkuDTO> skuVolumeList = skuList.stream()
                .filter(s -> s.getSkuVolume() != 0)
                .sorted((s1, s2) -> s1.getSkuVolume().compareTo(s2.getSkuVolume()))
                .collect(Collectors.toList());
        Map<String, Object> map = new HashMap<>();
        map.put("StockAgeRes", res);
        if ("volume".equals(req.getSortType())) {
            map.put("skuNumList", skuVolumeList.subList(skuNumList.size() >= 100 ? skuNumList.size() - 100 : 0, skuNumList.size()));
//            map.put("skuVolumeList", skuVolumeList.subList(skuVolumeList.size() >= 100 ? skuVolumeList.size() - 100 : 0, skuVolumeList.size()));
        } else {
            map.put("skuNumList", skuNumList.subList(skuNumList.size() >= 100 ? skuNumList.size() - 100 : 0, skuNumList.size()));
//            map.put("skuVolumeList", skuNumList.subList(skuVolumeList.size() >= 100 ? skuVolumeList.size() - 100 : 0, skuVolumeList.size()));
        }
        return SingleResult.success(map);
    }


}
